package com.tomasio.projects.lua.controllers;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import com.tomasio.projects.lua.api.MainService;
import com.tomasio.projects.lua.core.exception.CoreException;
import com.tomasio.projects.lua.forms.UserForm;
import com.tomasio.projects.lua.model.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 *
 * @author dctp
 */
@Controller
@RequestMapping("/users")
public class UsersController {

    private final MainService mainService;

    @Autowired
    public UsersController(MainService mainService) {
        this.mainService = mainService;
    }

    @RequestMapping({"/", "/index", ""})
    public String index(Model model, WebRequest request) {

        List<Map<Object, Object>> dataList = new ArrayList<Map<Object, Object>>();

        List<User> users = mainService.listUsers();

        for (User user : users) {
            Map<Object, Object> item = new HashMap<Object, Object>();

            item.put("uid", user.getUid());
            item.put("title", user.getTitle());
            item.put("name", user.getName());
            item.put("login", user.getLogin());
            item.put("email", user.getEmail());
            item.put("organization", user.getOrganization());
            

            dataList.add(item);
        }

        model.addAttribute("total", dataList.size());
        model.addAttribute("dataList", dataList);

        return "users";
    }

    @RequestMapping("/new")
    public String newUser(Model model) {

        UserForm form = new UserForm();
        model.addAttribute(form);
        return "users/form";
    }

    @RequestMapping("/edit")
    public String editUser(Model model, WebRequest request) {
        UserForm form = new UserForm();
        String uidParam = request.getParameter("uid");
        if (uidParam == null) {
            return "redirect:index";
        }
        

        User user = mainService.findUser(uidParam);
        form.setUid(user.getUid());
        form.setName(user.getName());
        form.setEmail(user.getEmail());
        form.setLogin(user.getLogin());
        form.setOrganization(user.getOrganization());
        form.setPhoneNumber(user.getPhoneNumber());
        form.setSurname(user.getSurname());
        form.setTitle(user.getTitle());
        //form.setDescription(user.getDescription());
        model.addAttribute(form);
        return "users/form";
    }

    @RequestMapping("/save")
    public String saveUser(Model model, @Valid UserForm form,
            BindingResult bindingResult, WebRequest request) {

        if (bindingResult.hasErrors()) {
            return "users/form";
        }

        User user = new User();
        user.setUid(form.getUid());
        user.setName(form.getName());
        user.setEmail(form.getEmail());
        user.setGivenName(form.getTitle() + form.getSurname());
        user.setLogin(form.getLogin());
        user.setOrganization(form.getOrganization());
        user.setPhoneNumber(form.getPhoneNumber());
        user.setSurname(form.getSurname());
        

        try {
            if (user.getUid() == null) {
                String uid = mainService.createUser(user);
                user.setUid(uid);
                model.addAttribute("successMessage", "Aplicação adicionada com sucesso!");
            } else {
                mainService.updateUser(user);
                model.addAttribute("successMessage", "Aplicação atualizada com sucesso!");
            }

        } catch (CoreException ex) {
            model.addAttribute("errorMessage", ex.getMessage());
            return "users/form";
        }

       

        model.addAttribute("data", user);

        return "users/detail";

    }

    @RequestMapping("/detail")
    public String detailUser(Model model, WebRequest request) {
        Map<Object, Object> data = new HashMap<Object, Object>();
        String uidParam = request.getParameter("uid");
        if (uidParam == null) {
            return "redirect:index";
        }
        
        User user = mainService.findUser(uidParam);

       

        model.addAttribute("data", user);
        return "users/detail";
    }

    @RequestMapping("/remove")
    public String removeUser(Model model, WebRequest request,
            final RedirectAttributes redirectAttributes) {
       
        String uidParam = request.getParameter("uid");
        if (uidParam == null) {
            return "redirect:index";
        }
       

        try {
            mainService.removeUser(uidParam);
            redirectAttributes.addFlashAttribute("successMessage", "Usuário foi removido com sucesso!");

        } catch (CoreException ex) {
            redirectAttributes.addFlashAttribute("errorMessage", ex.getMessage());
            return "redirect:index";
        }

        return "redirect:index";
    }
}
